package com.zm.shop.listener;

import com.rabbitmq.client.Channel;
import com.zm.shop.common.constants.RabbitMQCons;
import com.zm.shop.common.entity.SmsEntity;
import com.zm.shop.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class SmsListener {

    @Value("${sms.host}")
    private String host;

    @Value("${sms.path}")
    private String path;

    @Value("${sms.appCode}")
    private String appCode;

    @Value("${sms.method}")
    private String method;

    @RabbitListener(queues = RabbitMQCons.SMS_QUEUE)
    public void send(SmsEntity smsEntity, Channel channel, Message message) {
        // 1.创建一个Map用来封装发送短信的信息
        Map<String,String> headers=new HashMap<>();
        headers.put("Authorization", "APPCODE " + appCode);

        // 2.把信息全封装到Map中
        Map<String,String> querys = new HashMap<>();
        querys.put("phone",smsEntity.getPhone());
        querys.put("templateId",smsEntity.getTempId());
        querys.put("code",smsEntity.getCode());
        System.out.println("手机验证码是"+querys.get("code"));
        try {
            //3.通过阿里云接口发送短信
            //HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, new HashMap<String, String>());
            //log.debug("resp:{}", EntityUtils.toString(response.getEntity(), "utf-8"));   // 解析响应的内容
            //4.消费sms消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            log.error("MQ ACK 异常", e);
        }catch (Exception e) {
            log.error("发送短信失败", e);
        }

    }

}
